import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import {
  UntypedFormBuilder,
  UntypedFormGroup,
  Validators,
} from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalModule } from 'ng-zorro-antd/modal';
import { RESPONSE_CODE } from 'src/app/share/const/base.const';
import { RESPONSE_DATA } from 'src/app/share/const/interfaces';
import { ScenarioService } from 'src/app/share/service/scenario.service';

@Component({
  selector: 'app-add-scenario',
  templateUrl: './add.scenario.component.html',
  // styleUrls: [''],
})
export class AddScenarioComponent implements OnInit {
  @Output() addComplete = new EventEmitter<number>();

  isAddVisible = false;
  // 新增form
  addForm!: UntypedFormGroup;

  ngOnInit(): void {
    this.initAddForm();
  }

  constructor(
    private fb: UntypedFormBuilder,
    private service: ScenarioService,
    private message: NzMessageService
  ) {}

  // 显示新增弹窗
  showAddModal() {
    this.initAddForm();
    this.isAddVisible = true;
  }

  initAddForm() {
    this.addForm = this.fb.group({
      scenario: [null, Validators.required],
      description: [null, Validators.required],
    });
  }

  handleCancel() {
    this.isAddVisible = false;
  }

  handleAddOk() {
    // 先触发手动验证
    Object.values(this.addForm.controls).forEach((control) => {
      if (control.invalid) {
        control.markAsDirty();
        control.updateValueAndValidity({ onlySelf: true });
      }
    });

    if (this.addForm.valid) {
      const value = this.addForm.value;
      this.service.postScenario(value).subscribe((res) => {
        const { code, msg, data } = res as RESPONSE_DATA;
        if (code == RESPONSE_CODE.SUCCESS) {
          // console.log('data---', data);
          // 创建成功后,把Scenario id返回给父组件, 用于创建关联关系
          this.message.success('创建成功');
          this.isAddVisible = false;
          this.addComplete.emit(data.id);
        } else {
          this.message.error(msg);
        }
      });
    }
  }
}
